import {forwardRef, useEffect, useImperativeHandle, useState} from "react";
import {Button, Card, List, message, Modal, Row, Space} from "antd";
import {addChapterContentAPI} from "../../../../apis/novel.js";
import {useLocation} from "react-router-dom";

const ShowChapterDialog = forwardRef((props, ref) => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const location = useLocation();


    useImperativeHandle(ref, () => ({
        toggleShowChapterDialog: (isOpen) => {
            setIsModalOpen(isOpen);
        },
    }));


    // 新增书籍章节
    const addChapter = async () => {

        let data = {
            bookId: location.state.novelInfo.bookId,
            chapterHeadlines: props?.chapterList
        }

        console.log('111', data)
        let res = await addChapterContentAPI(data)

        console.log('新增书籍章节', res)
        if (res.code === '0000') {
            message.success('新增书籍章节成功')
            props.getChapter()
        } else {
            message.error('新增书籍章节失败')
        }
        setIsModalOpen(false)
    }


    return (
        <>
            <Modal okText="确认" cancelText="取消" title="生成章节" open={isModalOpen}
                   onOk={() => addChapter()}
                   onCancel={() => setIsModalOpen(false)}>

                <Row justify={"end"}>
                    <Button type={"primary"} onClick={() => {
                        props.reAddChapter()
                    }}>
                        重新生成
                    </Button>
                </Row>

                <List
                    style={{
                        maxHeight: '60vh',
                        overflow: 'auto'
                    }}
                    itemLayout="horizontal"
                    dataSource={props?.chapterList}
                    renderItem={(item, index) => (
                        <List.Item>
                            <List.Item.Meta
                                title={<span>{item.headline}</span>}
                                description={item.topic}
                            />
                        </List.Item>
                    )}
                />
            </Modal>
        </>
    );
});

export default ShowChapterDialog;